package droidninja.filepicker;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import droidninja.filepicker.fragments.DocFragment;
import droidninja.filepicker.fragments.DocPickerFragment;
import droidninja.filepicker.fragments.MediaPickerFragment;
import droidninja.filepicker.fragments.PhotoPickerFragmentListener;
import droidninja.filepicker.models.MediaResult;
import droidninja.filepicker.utils.FilePickerUtils;
import droidninja.filepicker.utils.FileUtils;
import droidninja.filepicker.utils.FragmentUtil;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FilePickerActivity extends BaseFilePickerActivity implements
        PhotoPickerFragmentListener,
        DocFragment.DocFragmentListener,
        DocPickerFragment.DocPickerFragmentListener,
        MediaPickerFragment.MediaPickerFragmentListener {

    private static final String TAG = FilePickerActivity.class.getSimpleName();
    private int type;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.activity_file_picker);
    }


    @Override
    protected void initView() {
        Intent intent = getIntent();
        if (intent != null) {
            if (getSupportActionBar() != null)
                getSupportActionBar().setDisplayHomeAsUpEnabled(true);

            ArrayList<String> selectedPaths = intent.getStringArrayListExtra(FilePickerConst.KEY_SELECTED_MEDIA);
            type = intent.getIntExtra(FilePickerConst.EXTRA_PICKER_TYPE, FilePickerConst.MEDIA_PICKER);

            if (selectedPaths != null) {

                if (PickerManager.getInstance().getMaxCount() == 1) {
                    selectedPaths.clear();
                }

                PickerManager.getInstance().clearSelections();
                if (type == FilePickerConst.MEDIA_PICKER) {
                    PickerManager.getInstance().add(selectedPaths, FilePickerConst.FILE_TYPE_MEDIA);
                } else {
                    PickerManager.getInstance().add(selectedPaths, FilePickerConst.FILE_TYPE_DOCUMENT);
                }
            } else
                selectedPaths = new ArrayList<>();

            setToolbarTitle(PickerManager.getInstance().getCurrentCount());
            openSpecificFragment(type, selectedPaths);
        }
    }

    private void setToolbarTitle(int count) {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            int maxCount = PickerManager.getInstance().getMaxCount();
            if (maxCount == -1 && count > 0)
                actionBar.setTitle(String.format(getString(R.string.attachments_num), count));
            else if (maxCount > 0 && count > 0)
                actionBar.setTitle(String.format(getString(R.string.attachments_title_text), count, maxCount));
            else {
                if (type == FilePickerConst.MEDIA_PICKER)
                    actionBar.setTitle(R.string.select_photo_text);
                else
                    actionBar.setTitle(R.string.select_doc_text);
            }
        }

    }

    private void openSpecificFragment(int type, @Nullable ArrayList<String> selectedPaths) {
        if (type == FilePickerConst.MEDIA_PICKER) {
            MediaPickerFragment photoFragment = MediaPickerFragment.newInstance();
            FragmentUtil.addFragment(this, R.id.container, photoFragment);
        } else {
            if (PickerManager.getInstance().isDocSupport())
                PickerManager.getInstance().addDocTypes();

            DocPickerFragment photoFragment = DocPickerFragment.newInstance();
            FragmentUtil.addFragment(this, R.id.container, photoFragment);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.picker_menu, menu);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int i = item.getItemId();
        if (i == R.id.action_done) {
            if (type == FilePickerConst.MEDIA_PICKER)
                returnData(PickerManager.getInstance().getSelectedPhotos());
            else
                returnData(PickerManager.getInstance().getSelectedFiles());

            return true;
        } else if (i == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        PickerManager.getInstance().reset();
        setResult(RESULT_CANCELED);
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case FilePickerConst.REQUEST_CODE_MEDIA_DETAIL:
                if (resultCode == Activity.RESULT_OK) {
                    if (type == FilePickerConst.MEDIA_PICKER)
                        returnData(PickerManager.getInstance().getSelectedPhotos());
                    else
                        returnData(PickerManager.getInstance().getSelectedFiles());
                } else {
                    setToolbarTitle(PickerManager.getInstance().getCurrentCount());
                }
                break;
        }
    }

    private void returnData(ArrayList<String> paths) {
        if (type == FilePickerConst.MEDIA_PICKER) {
            // 这里需要对图片进行压缩 ， 需要在工作线程中进行压缩
            showLoading("文件处理中，请稍后...");
            getIo().execute(new Runnable() {
                @Override
                public void run() {
                    // 获取最小压缩大小
                    long m = PickerManager.getInstance().getMinCompressSize();
                    ArrayList<String> fileNewList = new ArrayList<>();
                    if (m == 0) {
                        // 不需要进行压缩
                        fileNewList.addAll(paths);
                    } else {
                        for (String path : paths) {
                            File file = new File(path);
                            long fileSourceSize = FileUtils.fileSize(file);
                            if (fileSourceSize > m) {
                                // 大于1M的都需要压缩
                                try {
                                    // 对文件进行压缩
                                    List<File> fileList = Luban.with(FilePickerActivity.this)  //context
                                            .load(file)  // 需要压缩的图片file
                                            .ignoreBy(getLeastCompressSize())   //压缩率 ，默认100
                                            .setTargetDir(file.getParent())  //压缩后文件目录
                                            .filter(new CompressionPredicate() {
                                                @Override
                                                public boolean apply(String path) {
                                                    return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                                                }
                                            }).get();
                                    // 这里一次只压缩一次文件
                                    File compressFile = fileList.get(0);
                                    // 文件重命名
                                    // 删除之前的文件，对压缩的文件进行重名名
                                    String fileStart = path.split("\\.")[0];
                                    String fileEnd = compressFile.getAbsolutePath().split("\\.")[1];
                                    String imagePathNew = fileStart + "." + fileEnd;
                                    boolean delete = file.delete();
                                    boolean renameTo = compressFile.renameTo(new File(imagePathNew));
                                    if (delete && renameTo) {
                                        fileNewList.add(imagePathNew);
                                    }
                                    if (BuildConfig.DEBUG) {
                                        String fileSize = FileUtils.formatFileSize(imagePathNew);
                                        Log.i(TAG, "imagePath: " + path + " file:" + compressFile.getAbsolutePath() + " length：" + fileSize);
                                        Log.i(TAG, "delete: " + delete + " renameTo:" + renameTo);
                                        Log.i(TAG, "imagePathNew: " + imagePathNew);
                                        Log.i(TAG, "fileStart: " + fileStart + " fileEnd:" + fileEnd);
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            } else {
                                fileNewList.add(path);
                            }
                        }
                    }
                    // 文件压缩完成
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            FilePickerUtils.notifyMediaStore(FilePickerActivity.this,
                                    fileNewList, new MediaResult.OnMediaResultListener() {
                                @Override
                                public void onMediaResult(MediaResult result) {
                                    hideLoading();
                                    Intent intent = new Intent();
                                    intent.putStringArrayListExtra(FilePickerConst.KEY_SELECTED_MEDIA, fileNewList);
                                    setResult(RESULT_OK, intent);
                                    finish();
                                }
                            });
                        }
                    });
                }
            });
        } else {
            Intent intent = new Intent();
            intent.putStringArrayListExtra(FilePickerConst.KEY_SELECTED_DOCS, paths);
            setResult(RESULT_OK, intent);
            finish();
        }

    }

    @Override
    public void onItemSelected() {
        int currentCount = PickerManager.getInstance().getCurrentCount();
        setToolbarTitle(currentCount);

        if (PickerManager.getInstance().getMaxCount() == 1 && currentCount == 1)
            returnData(type == FilePickerConst.MEDIA_PICKER ? PickerManager.getInstance().getSelectedPhotos() : PickerManager.getInstance().getSelectedFiles());
    }
}
